package com.tg.client.hystrix;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableCircuitBreaker
public class CacheMain {
    public static void main(String[] args) {
        SpringApplication.run(CacheMain.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Autowired
    private CustomerService customerService;

    @GetMapping("/getCustomer")
    public String getCustomer(String id) {
        //初始化Hystrix请求上下文
        HystrixRequestContext.initializeContext();
        String c1 = customerService.getCustomer(id);

        String c2 = customerService.getCustomer(id);

        customerService.clearCache(id);

        String c3 = customerService.getCustomer(id);

        return String.format("%s:%s:%s", c1, c2, c3);
    }

    @GetMapping("/clearCache")
    public String clearCache(String id) {
        return customerService.clearCache(id);
    }
}
